#!/usr/bin/python
# -*- coding: utf-8 -*-  # 编码声明，确保支持非 ASCII 字符

import json
import time
import sys
import common
try:
    # Python 2
    import urllib
    import urllib2
    import httplib
except ImportError:
    # Python 3
    import urllib.request as urllib_request
    import urllib.parse as urllib_parse
    import http.client as httplib
    
def get_centos_version():
    version = ""
    try:
        with open("/etc/os-release", "r") as f:
            for line in f:
                if line.startswith("VERSION_ID"):
                    version = line.split("=")[1].strip().replace('"', '')
                    break
    except FileNotFoundError:
        return "Unknown"
    return version

# 制备一个开机自启动脚本
def prepare_start_script():
    # 安装一个nano软件
    common.execute_command("yum install -y nano")
    # 写入开机自启动脚本
    common.execute_command("nano /etc/systemd/system/my_script.service")
    with open("/etc/systemd/system/my_script.service", "w") as file:
        file.write("[Unit]\n")
        file.write("Description=My Python Script\n")
        file.write("After=network.target\n")
        file.write("\n")
        file.write("[Service]\n")
        file.write("ExecStart=/usr/bin/python3 /path/to/your_script.py\n")
        file.write("WorkingDirectory=/path/to\n")
        file.write("StandardOutput=journal\n")
        file.write("StandardError=inherit\n")
        file.write("Restart=always\n")
        file.write("User=your_user_name\n")
        file.write("Group=your_group_name\n")
        file.write("\n")
        file.write("[Install]\n")
        file.write("WantedBy=multi-user.target\n")

    # 启用开机自启动脚本
    common.execute_command("systemctl daemon-reload")
    common.execute_command("systemctl enable my_script.service")


# 执行迁移命令
def execute_transfer_command():
    common.execute_command("cat /proc/sys/fs/binfmt_misc")
    
    common.execute_command("unshare --mount bash")
    
    common.execute_script("./run-env", ["install"])
    
    if 0 == common.execute_script("./cqos-leapp", ["preupgrade", "--no-rhsm"]):
        print("cqos-leapp preupgrade --no-rhsm 执行成功")
        common.execute_script("./cqos-leapp", ["upgrade", "--resume"])
        if get_centos_version().startswith("8"):
            common.execute_script("./cqos-leapp", ["postupgrade", "--no-rhsm"])
        else:
            common.execute_script("./cqos-leapp", ["postupgrade", "--resume"])
    else:
        print("cqos-leapp preupgrade --no-rhsm 执行失败")
        sys.exit(1)

def main():

    # 准备开机自启动脚本
    prepare_start_script()
    # 执行迁移命令
    execute_transfer_command()
    
    


if __name__ == '__main__':
    main()